<?php
declare (strict_types = 1);

namespace app\common\model;

use think\Model;

/**
 * @mixin \think\Model
 */
class Question extends Model
{
    // public $typeMap = [
    //     ['value' => 0, 'text' => '上句'],
    //     ['value' => 1, 'text' => '上句'],
    // ];

    //
    public function poem()
    {
        return $this->hasOne(Poem::class, 'id', 'poem_id');
    }

    // public function getTypeAttr($value)
    // {
    //     return $this->typeMap[$value];
    // }

    public function getFirstAttr()
    {
        return $this->poem->getLine($this->line)[0];
    }

    public function getSecondAttr()
    {
        return $this->poem->getLine($this->line)[1];
    }

    /**
     * Undocumented function
     *
     * @param User $user
     * @param integer $ratio
     * @return Question
     * @author Ymob
     * @date 2021-04-25 02:20:43
     */
    public static function getQuestion($user, $ratio = 3)
    {
        $question = self::where([
            ['hide', '=', 0],
            ['question.id', '>', $user->last_question_id + $ratio],
        ])->where('id', 'NOT IN', function ($query) use ($user) {
            $query->table('anwser')->where('user_id', $user->id)->field('question_id');
        })->find();

        if (!$question) {
            if ($ratio == 3) {
                $question = self::getQuestion($user, 1);
            }
            if (!$question) {
                $question = self::where([
                    'hide' => 0,
                ])->where('id', 'NOT IN', function ($query) use ($user) {
                    $query->table('anwser')->where('user_id', $user->id)->field('question_id');
                })->find();
            }
        }

        return $question;
    }
}
